package com.atguigu.gmall.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.utils.DateFormatUtil;
import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @author Felix
 * @date 2023/2/22
 * 流量域：日志数据分流
 * 需要启动的进程
 *      zk、kafka、flume、DwdTrafficBaseLogSplit
 */
public class DwdTrafficBaseLogSplit {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        /*//TODO 2.检查点相关设置
        //2.1 开启检查点
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(6000L);
        //2.3 设置job取消之后检查点是否保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 设置两个检查点之间最小的时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        //2.5 设置重启策略
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
        //2.6 设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop202:8020/gmall/ck");*/
        //2.7 设置操作hadoop的用户
        System.setProperty("HADOOP_USER_NAME","atguuigu");

        //TODO 3.从kafka的主题中读取日志数据
        //3.1 声明消费的主题以及消费者组
        String topic = "topic_log";
        String groupId = "dwd_traffic_log_split_group";
        //3.2 创建消费者对象
        KafkaSource<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        //3.3 消费数据 封装为流
        DataStreamSource<String> kafkaStrDS = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafka_source");

        // kafkaStrDS.print(">>>>");
        //TODO 4.简单的ETL并对流中数据类型进行转换     脏数据写到侧输出流中
        //4.1 定义侧输出流标签
        OutputTag<String> dirtyTag = new OutputTag<String>("dirtyTag"){};
        //4.2 ETL以及转换
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
            new ProcessFunction<String, JSONObject>() {
                @Override
                public void processElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
                    try {
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        out.collect(jsonObj);
                    } catch (Exception e) {
                        //如果发生了异常，说明流中的数据不是标准的json，属于脏数据，放到侧输出流中
                        ctx.output(dirtyTag, jsonStr);
                    }
                }
            }
        );
        jsonObjDS.print(">>>>");
        SideOutputDataStream<String> dirtyDS = jsonObjDS.getSideOutput(dirtyTag);
        dirtyDS.print("####");

        //TODO 5.将侧输出流中的脏数据写到kafka的主题中
        dirtyDS.sinkTo(
            MyKafkaUtil.getKafkaSink("dirty_data","dirty")
        );

        //TODO 6.对新老访客标记进行修复    状态编程
        //6.1 按照mid进行分组
        KeyedStream<JSONObject, String> keyedDS
            = jsonObjDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));
        //6.2 修复
        SingleOutputStreamOperator<JSONObject> fixedDS = keyedDS.map(
            new RichMapFunction<JSONObject, JSONObject>() {
                //状态声明  该状态用于存放当前设备上次访问日期
                private ValueState<String> lastVisitDateState;

                @Override
                public void open(Configuration parameters) throws Exception {

                    ValueStateDescriptor<String> valueStateDescriptor
                        = new ValueStateDescriptor<String>("lastVisitDateState", String.class);
                    lastVisitDateState = getRuntimeContext().getState(valueStateDescriptor);
                }

                @Override
                public JSONObject map(JSONObject jsonObj) throws Exception {
                    String isNew = jsonObj.getJSONObject("common").getString("is_new");
                    String lastVisitDate = lastVisitDateState.value();
                    Long ts = jsonObj.getLong("ts");
                    String curVisitDate = DateFormatUtil.toDate(ts);

                    if ("1".equals(isNew)) {
                        //如果is_new的值为1
                        if (StringUtils.isEmpty(lastVisitDate)) {
                            //如果键控状态为null，认为本次是该访客首次访问 APP，将日志中 ts 对应的日期更新到状态中，不对 is_new 字段做修改；
                            lastVisitDateState.update(curVisitDate);
                        } else {
                            //如果键控状态不为null，且首次访问日期不是当日，说明访问的是老访客，将 is_new 字段置为 0；
                            if (!lastVisitDate.equals(curVisitDate)) {
                                isNew = "0";
                                jsonObj.getJSONObject("common").put("is_new", isNew);
                            }
                        }
                    } else {
                        //如果 is_new 的值为 0
                        //如果键控状态为 null，说明访问 APP 的是老访客但本次是该访客的页面日志首次进入程序。当前端新老访客状态标记丢失时，日志进入程序被判定为新访客，Flink 程序就可以纠正被误判的访客状态标记，只要将状态中的日期设置为今天之前即可。本程序选择将状态更新为昨日；
                        if (StringUtils.isEmpty(lastVisitDate)) {
                            Long yesterDayMS = ts - 24 * 60 * 60 * 1000;
                            String yesterDay = DateFormatUtil.toDate(yesterDayMS);
                            lastVisitDateState.update(yesterDay);
                        }
                    }
                    return jsonObj;
                }
            }
        );

        fixedDS.print(">>>");

        //TODO 7.分流   错误日志-错误侧输出流 启动日志-启动侧输出流 曝光日志-曝光侧输出流 动作日志-动作侧输出流 页面日志-主流
        //7.1 定义侧输出流标签
        OutputTag<String> errTag = new OutputTag<String>("errTag") {};
        OutputTag<String> startTag = new OutputTag<String>("startTag") {};
        OutputTag<String> displayTag = new OutputTag<String>("displayTag") {};
        OutputTag<String> actionTag = new OutputTag<String>("actionTag") {};
        //7.2 分流
        SingleOutputStreamOperator<String> pageDS = fixedDS.process(
            new ProcessFunction<JSONObject, String>() {
                @Override
                public void processElement(JSONObject jsonObj, Context ctx, Collector<String> out) throws Exception {
                    //处理错误日志
                    JSONObject errJsonObj = jsonObj.getJSONObject("err");
                    if (errJsonObj != null) {
                        ctx.output(errTag, errJsonObj.toJSONString());
                        jsonObj.remove("err");
                    }
                    JSONObject startJsonObj = jsonObj.getJSONObject("start");
                    if (startJsonObj != null) {
                        //处理启动日志
                        ctx.output(startTag, jsonObj.toJSONString());
                    } else {
                        //处理页面日志
                        JSONObject commonJsonObj = jsonObj.getJSONObject("common");
                        JSONObject pageJsonObj = jsonObj.getJSONObject("page");
                        Long ts = jsonObj.getLong("ts");

                        //处理曝光数据
                        JSONArray displayArr = jsonObj.getJSONArray("displays");
                        if (displayArr != null && displayArr.size() > 0) {
                            for (int i = 0; i < displayArr.size(); i++) {
                                JSONObject displayJsonObj = displayArr.getJSONObject(i);
                                //创建一个新的对象，用于封装曝光信息
                                JSONObject newDisplayJsonObj = new JSONObject();
                                newDisplayJsonObj.put("common", commonJsonObj);
                                newDisplayJsonObj.put("page", pageJsonObj);
                                newDisplayJsonObj.put("ts", ts);
                                newDisplayJsonObj.put("display", displayJsonObj);
                                ctx.output(displayTag, newDisplayJsonObj.toJSONString());
                            }
                            jsonObj.remove("displays");
                        }

                        //处理动作日志
                        JSONArray actionArr = jsonObj.getJSONArray("actions");
                        if (actionArr != null && actionArr.size() > 0) {
                            for (int i = 0; i < actionArr.size(); i++) {
                                JSONObject actionJsonObj = actionArr.getJSONObject(i);
                                JSONObject newActionJsonObj = new JSONObject();
                                newActionJsonObj.put("common", commonJsonObj);
                                newActionJsonObj.put("page", pageJsonObj);
                                newActionJsonObj.put("action", actionJsonObj);
                                ctx.output(actionTag, newActionJsonObj.toJSONString());
                            }
                            jsonObj.remove("actions");
                        }

                        //页面日志放到主流中
                        out.collect(jsonObj.toJSONString());
                    }
                }
            }
        );
        //TODO 8.将不同流的数据写到kafka的主题中
        SideOutputDataStream<String> errDS = pageDS.getSideOutput(errTag);
        SideOutputDataStream<String> startDS = pageDS.getSideOutput(startTag);
        SideOutputDataStream<String> displayDS = pageDS.getSideOutput(displayTag);
        SideOutputDataStream<String> actionDS = pageDS.getSideOutput(actionTag);

        pageDS.print(">>>");
        errDS.print("###");
        startDS.print("$$$");
        displayDS.print("&&&");
        actionDS.print("@@@");

        pageDS.sinkTo(MyKafkaUtil.getKafkaSink("dwd_traffic_page_log","page"));
        errDS.sinkTo(MyKafkaUtil.getKafkaSink("dwd_traffic_err_log","err"));
        startDS.sinkTo(MyKafkaUtil.getKafkaSink("dwd_traffic_start_log","start"));
        displayDS.sinkTo(MyKafkaUtil.getKafkaSink("dwd_traffic_display_log","display"));
        actionDS.sinkTo(MyKafkaUtil.getKafkaSink("dwd_traffic_action_log","action"));
        env.execute();
    }
}
